package com.ericsson.bscs.cmstest.clients ;

import java.io.InputStream ;
import java.util.Map ;
import java.util.Properties ;
import java.util.logging.Logger ;

import org.omg.CORBA.Object ;
import org.omg.CosNaming.NamingContextExt ;

import com.lhs.ccb.common.soi.AccessorFactory ;
import com.lhs.ccb.common.soi.ExchangeFormatFactory ;
import com.lhs.ccb.common.soi.InvalidParameterTypeException ;
import com.lhs.ccb.common.soi.ParameterList ;
import com.lhs.ccb.common.soi.RootAccessor ;
import com.lhs.ccb.common.soi.SVLMoney ;
import com.lhs.ccb.common.soi.SVLObject ;
import com.lhs.ccb.common.soi.SVLObjectList ;
import com.lhs.ccb.common.soi.SVLType ;
import com.lhs.ccb.common.soi.ServiceAccessor ;
import com.lhs.ccb.common.soi.ServiceLayerIntrospector ;
import com.lhs.ccb.common.soi.SignatureMismatchException ;
import com.lhs.ccb.common.soiimpl.DefaultSVLObjectFactory ;
import com.lhs.ccb.common.soiimpl.NvElementFactory ;
import com.lhs.ccb.common.soiimpl.RemoteParameterListLoader ;
import com.lhs.ccb.func.corba.CORBAAdapter ;
import com.lhs.ccb.func.ect.ComponentException ;
import com.lhs.ccb.soi.ErrorInfoI ;

/**
 * @author Igor Kostin: igor.kstn@gmail.com
 * 
 */
public class BaseTestHandler
{
	private static Logger _logger = Logger.getLogger(BaseTestHandler.class.getCanonicalName()) ;

	public static final String WRITE_BILLING_ACCOUNT_CMD = "BILLING_ACCOUNT.WRITE" ;
	public static final String WRITE_CONTRACT_CMD = "CONTRACT.WRITE" ;
	public static final String WRITE_SERVICE_CMD = "CONTRACT_SERVICES.WRITE" ;
	public static final String WRITE_PARAM_CMD = "CONTRACT_SERVICE_PARAMETERS.WRITE" ;
	public static final String ADD_SERVICE_CMD = "CONTRACT_SERVICES.ADD" ;
	public static final String READ_SERVICE_CMD = "CONTRACT_SERVICES.READ" ;
	public static final String READ_PARAM_CMD = "CONTRACT_SERVICE_PARAMETERS.READ" ;
	public static final String READ_CONTRACT_CMD = "CONTRACT.READ" ;
	public static final String WRITE_BILLING_ACCOUNT_ASSIGNMENT_CMD = "BILLING_ACCOUNT_ASSIGNMENT.WRITE" ;
	public static final String NEW_CONTRACT_PREPAID_DATA_CMD = "CONTRACT_PREPAID_DATA.NEW" ;
	public static final String PRODUCT_CHANGE_CMD = "PRODUCT.CHANGE" ;
	public static final String REQUESTS_SEARCH_CMD = "REQUESTS.SEARCH" ;
	public static final String WRITE_PROMISED_PAYMENT_CMD = "PROMISED_PAYMENT.WRITE" ;
	public static final String WRITE_CUSTOMER_HIERARCHY_CMD = "CUSTOMER_HIERARCHY.WRITE" ;
	public static final String START_BALANCE_INQUIRY_CMD = "BALANCE_INQUIRY.START" ;
	public static final String USAGE_DATA_RECORDS_READ_CMD = "USAGE_DATA_RECORDS.READ" ;
	public static final String CUSTOMER_BONUSPOINT_READ_CMD = "CUSTOMER_BONUSPOINT.READ" ;

	public static final String TARGET_SERVER = System.getenv("TARGET_SERVER") ;
	private ServiceAccessor cms ;
	private AccessorFactory _factory ;

	public void commit() throws ComponentException
	{
		cms.commit() ;
	}

	// lookup Server and login
	public void connect() throws ComponentException
	{
		// initialize naming service
		final NamingContextExt initialNamingContext = CORBAAdapter.instance().getInitialNamingContext() ;

		// find a CORBA Object in the naming context
		final Object corbaRootObj = CORBAAdapter.instance().findCorbaObject(initialNamingContext, TARGET_SERVER) ;

		// obtain a reference to a ServiceRootI
		final RootAccessor serviceRoot = ExchangeFormatFactory.instance().createRootAccessor(corbaRootObj) ;

		// login into the server
		_factory = serviceRoot.login("ERICSSON", "VELCOM", null) ;

		// obtain (get) a client session object
		cms = _factory.getServiceAccessor("CIL", "3_VEL_1") ;
	}

	public void disconnect()
	{
		cms.dispose() ;
		_factory.dispose() ;
	}

	public void display(final SVLObject svlobject, final int level) throws InvalidParameterTypeException, SignatureMismatchException
	{
		final String[] names = svlobject.getAttributeNames() ;
		String dspLine = "" ;
		// try {
		String indent = "" ;
		for (int iLevel = 0; iLevel < level; iLevel++)
			indent = indent + "\t" ;

		_logger.info("Command executed: " + "names.lenght=" + names.length) ;
		for (final String name : names)
		{
			final SVLType type = svlobject.getSVLType(name) ;
			dspLine = indent + name + ":" + type.toString() + "=" ;
			if (type.value() == SVLType._SVL_STRING)
				dspLine = dspLine + svlobject.getStringValue(name) ;
			else if (type.value() == SVLType._SVL_INTEGER)
				dspLine = dspLine + svlobject.getIntValue(name) ;
			else if (type.value() == SVLType._SVL_CHAR)
				dspLine = dspLine + svlobject.getCharValue(name) ;
			else if (type.value() == SVLType._SVL_LONG)
				dspLine = dspLine + svlobject.getLongValue(name) ;
			else if (type.value() == SVLType._SVL_BOOLEAN)
				dspLine = dspLine + svlobject.getBooleanValue(name) ;
			else if (type.value() == SVLType._SVL_DATE)
				dspLine = dspLine + svlobject.getDateValue(name) ;
			else if (type.value() == SVLType._SVL_DATETIME)
				dspLine = dspLine + svlobject.getDateTimeValue(name) ;
			else if (type.value() == SVLType._SVL_MONEY)
				dspLine = dspLine + svlobject.getMoneyValue(name) ;
			else if (type.value() == SVLType._SVL_LIST)
			{
				final SVLObjectList items = svlobject.getSVLObjectList(name) ;
				_logger.info(dspLine) ;
				for (int j = 0; j < items.size(); j++)
				{
					_logger.info(indent + "[" + j + "]") ;
					final SVLObject svl = items.get(j) ;
					display(svl, level + 1) ;
				}
			} else if (type.value() == SVLType._SVL_LISTLIST)
			{
				final SVLObjectList items = svlobject.getSVLObjectList(name) ;
				_logger.info(dspLine) ;
				for (int j = 0; j < items.size(); j++)
				{
					_logger.info(indent + "[" + j + "]") ;
					final SVLObject svl = items.get(j) ;
					display(svl, level + 1) ;
				}
			}
			_logger.info(dspLine) ;
		}
		/*
		 * } catch (InvalidParameterTypeException iptex ) { iptex.printStackTrace(); } catch (SignatureMismatchException sigex) { sigex.printStackTrace(); }
		 * catch(Exception genEx){ genEx.printStackTrace(); }
		 */
	}

	public SVLObject executeCmsCommand(final ServiceAccessor cms, final Long contractID, final String cmd, final SVLObject input) throws Exception
	{
		ErrorInfoI result = new ErrorInfoI() ;
		SVLObject output = null ;
		try
		{
			output = cms.execute(cmd, input) ;
		}
		catch (final ComponentException ex)
		{
			result = NvElementFactory.createErrorInfoI(ex, null) ;
			if (contractID == null)
				System.err.println("Error in " + cmd + ": " + result.errorCode + "\n Info: " + result.message) ;
			else
				System.err.println(contractID.longValue() + ": Error in " + cmd + ": " + result.errorCode + "\n Info: " + result.message) ;
			throw new Exception(result.errorCode + " - " + result.message) ;
		}

		return output ;
	}

	public void getAvailableCommands()
	{
		final String[] commands = cms.getCommands() ;
		for (final String command : commands)
			System.out.println(command) ;
		System.out.println("\nNumber of commands: " + commands.length) ;
	}

	public void getAvailableSOIComponents() throws ComponentException
	{
		// use _factory and choose the right methods to retrieve all SOI
		// components
		// and the SOI versions which are available

		final String[] componentIds = _factory.getComponentIds() ;

		for (final String componentId : componentIds)
		{
			System.out.println(componentId) ;

			final String[] componentVersions = _factory.getComponentVersions(componentId) ;

			for (final String componentVersion : componentVersions)
				System.out.println("\t" + componentVersion) ;
		}
	}

	public ServiceAccessor getServiceAccessor()
	{
		return cms ;
	}

	public void handleBalanceInquiry(final ServiceAccessor cms, final String MSISDN, final Long notificationTypeId, final String tibcoSessId) throws Exception
	{
		final SVLObject balInquiryIn = ExchangeFormatFactory.instance().createSVLObject() ;

		balInquiryIn.setValue("DIRNUM", MSISDN) ;
		balInquiryIn.setValue("NOTIFICATION_TYPE", notificationTypeId) ;
		balInquiryIn.setValue("TIBCO_SESSION_ID", tibcoSessId) ;

		// BILLING_ACCOUNT.WRITE
		executeCmsCommand(cms, null, BaseTestHandler.START_BALANCE_INQUIRY_CMD, balInquiryIn) ;
	}

	public void handleBillingAccountAssignmentWrite(final ServiceAccessor cms, final Long coId, final Long baId) throws Exception
	{
		final SVLObject billingAcctAssignWriteInput = ExchangeFormatFactory.instance().createSVLObject() ;
		billingAcctAssignWriteInput.setValue("CO_ID", coId) ;
		billingAcctAssignWriteInput.setValue("BILLING_ACCOUNT_ID", baId) ;

		executeCmsCommand(cms, coId, BaseTestHandler.WRITE_BILLING_ACCOUNT_ASSIGNMENT_CMD, billingAcctAssignWriteInput) ;
		System.out.println(coId + " Billing Account Assignment Write Complete") ;
	}

	// TO_DO not a generic method, BZ_5399 specific
	public void handleBillingAccountCreate(final ServiceAccessor cms, final Long csId, final char invoicingInd, final Long creditClassId) throws Exception
	{
		final SVLObject billingAccCreateIn = ExchangeFormatFactory.instance().createSVLObject() ;

		billingAccCreateIn.setValue("CS_ID", csId) ;
		billingAccCreateIn.setValue("CREATE", Boolean.TRUE) ;
		billingAccCreateIn.setValue("PRIMARY_FLAG", false) ;
		billingAccCreateIn.setValue("INVOICING_IND", invoicingInd) ;
		billingAccCreateIn.setValue("CALL_DETAILS_FLAG", true) ;
		billingAccCreateIn.setValue("CREDIT_CLASS_ID", creditClassId) ;
		billingAccCreateIn.setValue("STATUS", 'A') ;

		// BILLING_ACCOUNT.WRITE
		executeCmsCommand(cms, csId, BaseTestHandler.WRITE_BILLING_ACCOUNT_CMD, billingAccCreateIn) ;
	}

	public void handleContractPrepaidDataNew(final ServiceAccessor cms, final Long coId, final Long prepaidProfileId, final char initialPrepaidState)
			throws Exception
	{
		final SVLObject newContractPrepaidDataInput = ExchangeFormatFactory.instance().createSVLObject() ;
		newContractPrepaidDataInput.setValue("CO_ID", coId) ;
		newContractPrepaidDataInput.setValue("PREPAID_PROFILE_ID", prepaidProfileId) ;
		newContractPrepaidDataInput.setValue("PREPAID_STATE", initialPrepaidState) ;

		executeCmsCommand(cms, coId, BaseTestHandler.NEW_CONTRACT_PREPAID_DATA_CMD, newContractPrepaidDataInput) ;
		System.out.println(coId + " Contract Prepaid Data New Complete") ;
	}

	public void handleContractWrite(final ServiceAccessor cms, final Long coId, final Long handlingReasonId, final String coPaymentType)
			throws ComponentException, Exception
	{
		final SVLObject writeContractInput = ExchangeFormatFactory.instance().createSVLObject() ;
		writeContractInput.setValue("CO_ID", coId) ;
		writeContractInput.setValue("HANDLING_REASON_ID", handlingReasonId) ;
		writeContractInput.setValue("CO_PAYMENT_TYPE", coPaymentType) ;

		executeCmsCommand(cms, coId, BaseTestHandler.WRITE_CONTRACT_CMD, writeContractInput) ;
		System.out.println(coId + " Contract Write Complete") ;
	}

	// TO_DO not a generic method, BZ_5399 specific
	public void handleCreditClassChange(final ServiceAccessor cms, final Long billingAccountId, final Long creditClassId) throws Exception
	{

		final SVLObject billingAccCreateIn = ExchangeFormatFactory.instance().createSVLObject() ;

		billingAccCreateIn.setValue("CREATE", Boolean.FALSE) ;
		billingAccCreateIn.setValue("BILLING_ACCOUNT_ID", billingAccountId) ;
		billingAccCreateIn.setValue("CREDIT_CLASS_ID", creditClassId) ;
		billingAccCreateIn.setValue("RESET_AVERAGE", Boolean.FALSE) ;

		// BILLING_ACCOUNT.WRITE
		executeCmsCommand(cms, billingAccountId, BaseTestHandler.WRITE_BILLING_ACCOUNT_CMD, billingAccCreateIn) ;
	}

	public void handleCustomerBonusPointsRead(final ServiceAccessor cms, final long customerId) throws Exception
	{
		final SVLObject customerBonusPointsReadIn = ExchangeFormatFactory.instance().createSVLObject() ;

		customerBonusPointsReadIn.setValue("CS_ID", customerId) ;

		// CUSTOMER_BONUSPOINTS.READ
		// SVLObject customerBonusPointsReadOut = ExchangeFormatFactory.instance().createSVLObject();
		final SVLObject customerBonusPointsReadOut = executeCmsCommand(cms, null, CUSTOMER_BONUSPOINT_READ_CMD, customerBonusPointsReadIn) ;

		display(customerBonusPointsReadOut, 1) ;
	}

	public void handleCustomerHierarchyWrite(final ServiceAccessor cms, final Long csIdHigh, final Long csId) throws Exception
	{
		final SVLObject customerHierarchyWriteIn = ExchangeFormatFactory.instance().createSVLObject() ;

		customerHierarchyWriteIn.setValue("CS_ID_HIGH", csIdHigh) ;
		customerHierarchyWriteIn.setValue("CS_ID", csId) ;

		// BILLING_ACCOUNT.WRITE
		executeCmsCommand(cms, csId, BaseTestHandler.WRITE_CUSTOMER_HIERARCHY_CMD, customerHierarchyWriteIn) ;
	}

	public void handleProductChange(final ServiceAccessor cms, final Long coId, final Long tmcode_new) throws Exception
	{
		final SVLObject productChangeInput = ExchangeFormatFactory.instance().createSVLObject() ;

		productChangeInput.setValue("CO_ID", coId) ;
		productChangeInput.setValue("NEW_RPCODE", tmcode_new) ;

		executeCmsCommand(cms, coId, BaseTestHandler.PRODUCT_CHANGE_CMD, productChangeInput) ;
		cms.commit() ;

		System.out.println(coId + " Product Change Complete") ;

		waitForPendingRequests(cms, coId) ;
	}

	public void handlePromisedPaymentWrite(final ServiceAccessor cms, final Long csId, final double inpAmnt, final Long BillingAccId,
			final Long handlingReasonId, final String promisedPaymentStatus) throws Exception
	{
		final SVLMoney amnt = ExchangeFormatFactory.instance().createSVLMoney(inpAmnt, "BYR") ;

		final SVLObject promisedPaymentWriteIn = ExchangeFormatFactory.instance().createSVLObject() ;

		promisedPaymentWriteIn.setValue("CS_ID", csId) ;
		promisedPaymentWriteIn.setValue("BILLING_ACCOUNT_ID", BillingAccId) ;
		promisedPaymentWriteIn.setValue("AMOUNT", amnt) ;
		promisedPaymentWriteIn.setValue("HANDLING_REASON_ID", handlingReasonId) ;
		promisedPaymentWriteIn.setValue("STATUS", promisedPaymentStatus) ;

		// BILLING_ACCOUNT.WRITE
		executeCmsCommand(cms, csId, BaseTestHandler.WRITE_PROMISED_PAYMENT_CMD, promisedPaymentWriteIn) ;
	}

	public void handleServiceAdd(final ServiceAccessor cms, final Long coId, final String service, final String spCodePub) throws Exception
	{
		final SVLObject addServiceInput = ExchangeFormatFactory.instance().createSVLObject() ;
		addServiceInput.setValue("CO_ID", coId) ;
		final SVLObjectList addServiceList = ExchangeFormatFactory.instance().createSVLObjectList() ;
		addServiceInput.setValue("services", addServiceList) ;
		final SVLObject serviceToAdd = ExchangeFormatFactory.instance().createSVLObject() ;
		addServiceList.add(serviceToAdd) ;
		serviceToAdd.setValue("SNCODE_PUB", service) ;
		serviceToAdd.setValue("SPCODE_PUB", spCodePub) ;
		serviceToAdd.setValue("PROFILE_ID", 0L) ;
		executeCmsCommand(cms, coId, BaseTestHandler.ADD_SERVICE_CMD, addServiceInput) ;
		System.out.println(coId + " Service Add Complete") ;
	}

	public void handleServiceParametersAct(final ServiceAccessor cms, final long coId, final String service, final String spCodePub, final String prm_desc,
			final Integer prm_value)
	{
		final SVLObject multValue = ExchangeFormatFactory.instance().createSVLObject() ;
		final SVLObjectList multValuesList = ExchangeFormatFactory.instance().createSVLObjectList() ;
		multValue.setValue("VALUE", String.valueOf(prm_value)) ;
		multValue.setValue("VALUE_DES", prm_desc) ;
		multValuesList.add(multValue) ;

		final SVLObject targetValue = ExchangeFormatFactory.instance().createSVLObject() ;
		final SVLObjectList targetValueList = ExchangeFormatFactory.instance().createSVLObjectList() ;
		targetValue.setValue("MULT_VALUES", multValuesList) ;
		targetValue.setValue("TARGET_SIBLING_NO", 1L) ;
		targetValueList.add(targetValue) ;

		final SVLObject paramValues = ExchangeFormatFactory.instance().createSVLObject() ;

		paramValues.setValue("COS_ACTION", 'a') ;
		paramValues.setValue("PRM_NO", 1L) ;
		paramValues.setValue("COMPLEX_NO", 1L) ;
		paramValues.setValue("COMPLEX_LEVEL", 1L) ;
		paramValues.setValue("SIBLING_NO", 1L) ;
		paramValues.setValue("PARENT_NO", 1L) ;
		paramValues.setValue("TARGET_PARAM_VALUES", targetValueList) ;

		final SVLObjectList paramValuesList = ExchangeFormatFactory.instance().createSVLObjectList() ;

		paramValuesList.add(paramValues) ;

		final SVLObject inp = ExchangeFormatFactory.instance().createSVLObject() ;

		inp.setValue("CO_ID", coId) ;
		inp.setValue("SPCODE_PUB", spCodePub) ;
		inp.setValue("SNCODE_PUB", service) ;
		inp.setValue("PROFILE_ID", 0L) ;
		inp.setValue("PARAM_VALUES", paramValuesList) ;
		try
		{
			System.out.println("CONTRACT_SERVICE_PARAMETERS.WRITE for CO_ID: " + String.valueOf(coId)) ;
			cms.execute(WRITE_PARAM_CMD, inp) ;
		}
		catch (final ComponentException ce)
		{
			System.err.println("Problem during invocation of CONTRACT_SERVICE_PARAMETERS.WRITE: " + ce.getMessage()) ;
		}
		System.out.println("For CO_ID: " + coId + " Parameters initialized.") ;
	}

	public void handleServicesAdd(final ServiceAccessor cms, final Long coId, final Map<String, String> snSpCodeMap) throws Exception
	{
		final SVLObject addServiceInput = ExchangeFormatFactory.instance().createSVLObject() ;
		addServiceInput.setValue("CO_ID", coId) ;
		final SVLObjectList addServiceList = ExchangeFormatFactory.instance().createSVLObjectList() ;
		addServiceInput.setValue("services", addServiceList) ;

		for (final Map.Entry<String, String> snSpEntry : snSpCodeMap.entrySet())
		{
			final SVLObject serviceToAdd = ExchangeFormatFactory.instance().createSVLObject() ;
			serviceToAdd.setValue("SNCODE_PUB", snSpEntry.getKey()) ;
			serviceToAdd.setValue("SPCODE_PUB", snSpEntry.getValue()) ;
			serviceToAdd.setValue("PROFILE_ID", 0L) ;
			addServiceList.add(serviceToAdd) ;
		}
		executeCmsCommand(cms, coId, BaseTestHandler.ADD_SERVICE_CMD, addServiceInput) ;
		System.out.println(coId + " Service Add Complete") ;
	}

	public void handleServicesWrite(final ServiceAccessor cms, final Long coId, final Map<String, String> snSpCodeMap, final int pendingStatus) throws Exception
	{
		final SVLObject activateServiceInput = ExchangeFormatFactory.instance().createSVLObject() ;
		activateServiceInput.setValue("CO_ID", coId) ;
		final SVLObjectList actServiceList = ExchangeFormatFactory.instance().createSVLObjectList() ;
		activateServiceInput.setValue("services", actServiceList) ;

		for (final Map.Entry<String, String> snSpEntry : snSpCodeMap.entrySet())
		{
			final SVLObject serviceToAct = ExchangeFormatFactory.instance().createSVLObject() ;
			serviceToAct.setValue("SNCODE_PUB", snSpEntry.getKey()) ;
			serviceToAct.setValue("SPCODE_PUB", snSpEntry.getValue()) ;
			serviceToAct.setValue("PROFILE_ID", 0L) ;
			serviceToAct.setValue("COS_PENDING_STATUS", pendingStatus) ;
			actServiceList.add(serviceToAct) ;
		}
		executeCmsCommand(cms, coId, BaseTestHandler.WRITE_SERVICE_CMD, activateServiceInput) ;
		System.out.println(coId + " Service Write Complete") ;
	}

	public void handleServiceWrite(final ServiceAccessor cms, final Long coId, final String service, final String spCodePub, final int pendingStatus)
			throws Exception
	{
		final SVLObject activateServiceInput = ExchangeFormatFactory.instance().createSVLObject() ;
		activateServiceInput.setValue("CO_ID", coId) ;
		final SVLObjectList actServiceList = ExchangeFormatFactory.instance().createSVLObjectList() ;
		activateServiceInput.setValue("services", actServiceList) ;
		final SVLObject serviceToAct = ExchangeFormatFactory.instance().createSVLObject() ;
		actServiceList.add(serviceToAct) ;
		serviceToAct.setValue("SNCODE_PUB", service) ;
		serviceToAct.setValue("SPCODE_PUB", spCodePub) ;
		serviceToAct.setValue("PROFILE_ID", 0L) ;
		serviceToAct.setValue("COS_PENDING_STATUS", pendingStatus) ;
		executeCmsCommand(cms, coId, BaseTestHandler.WRITE_SERVICE_CMD, activateServiceInput) ;
		System.out.println(coId + " Service Write Complete") ;
	}

	public void handleUsageDataRecordsRead(final ServiceAccessor cms, final Integer searchLimit, final Long csId, final Long coId) throws Exception
	{

		final SVLObject usageDataRecordsReadIn = ExchangeFormatFactory.instance().createSVLObject() ;

		usageDataRecordsReadIn.setValue("CS_ID", csId) ;
		usageDataRecordsReadIn.setValue("CO_ID", coId) ;
		usageDataRecordsReadIn.setValue("SEARCH_LIMIT", searchLimit) ;

		// USAGE_DATE_RECORDS.READ
		executeCmsCommand(cms, coId, BaseTestHandler.USAGE_DATA_RECORDS_READ_CMD, usageDataRecordsReadIn) ;
	}

	// initialize CORBA ORB
	protected void init() throws Exception
	{
		// initialize helper classes
		ExchangeFormatFactory.init(new DefaultSVLObjectFactory()) ;
		ServiceLayerIntrospector.setParameterListLoader(new RemoteParameterListLoader()) ;

		// create new object properties
		final Properties orbProps = new Properties() ;

		// read the orb.properties file

		final InputStream resourceAsStream = ClassLoader.getSystemResourceAsStream("orb.properties") ;
		orbProps.load(resourceAsStream) ;

		// put data into system properties
		System.getProperties().putAll(orbProps) ;

		// initialize ORB singleton with the configuration parameters from orb.properties
		CORBAAdapter.instance().initORB(null) ;
		CORBAAdapter.instance() ;
	}

	public void initializeBusinessUnit(final String pBuId) throws ComponentException
	{
		// create ServiceLayer object for input of SESSION.CHANGE - SVLObjects
		// are NameValue Container
		final SVLObject input = ExchangeFormatFactory.instance().createSVLObject() ;

		// create ServiceLayer object list for input parameter "values" of
		// SESSION.CHANGE command
		final SVLObjectList list_values = ExchangeFormatFactory.instance().createSVLObjectList() ;
		// set list of values as input parameter
		input.setValue("values", list_values) ;

		// create Service Layer object for setting of business unit (1st and
		// only list element of values)
		final SVLObject businessUnitSetting = ExchangeFormatFactory.instance().createSVLObject() ;
		// set value for KEY
		businessUnitSetting.setValue("KEY", "BU_ID_PUB") ;
		// set value for VALUE
		businessUnitSetting.setValue("VALUE", pBuId) ;
		// add element to list values
		list_values.add(businessUnitSetting) ;

		// initialize the session by calling command
		cms.execute("SESSION.CHANGE", input) ;
	}

	public void introspectionTest(final String pCmd) throws ComponentException
	{

		// get all input and output parameter of the SOI command which is past
		// to
		// the introspectionTest method

		final ParameterList inArgumentList = cms.getInArgumentList(pCmd) ;
		final String[] parameterNames = inArgumentList.getParameterNames() ;

		System.out.println("\nCommand: " + pCmd) ;
		System.out.println("\nInput Parameter: ") ;
		for (final String parameterName : parameterNames)
			System.out.println(parameterName) ;
		// System.out.println(inArgumentList.isMandatory(parameterNames[i]));

		final ParameterList OutArgumentList = cms.getOutArgumentList(pCmd) ;
		final String[] parameterOutNames = OutArgumentList.getParameterNames() ;

		System.out.println("\nOutput Parameter: ") ;
		for (final String parameterOutName : parameterOutNames)
			System.out.println(parameterOutName) ;
	}

	public void waitForPendingRequests(final ServiceAccessor cms, final Long coId) throws Exception
	{
		final SVLObject requestsInput = ExchangeFormatFactory.instance().createSVLObject() ;

		requestsInput.setValue("RE_SEARCH_MASK", 1) ;
		requestsInput.setValue("CO_ID", coId) ;

		boolean hasRequest = true ;
		while (hasRequest)
		{
			System.out.println(coId + " Waiting for pending requests...") ;
			final SVLObject requestsOutput = executeCmsCommand(cms, coId, BaseTestHandler.REQUESTS_SEARCH_CMD, requestsInput) ;
			final SVLObjectList requestList = requestsOutput.getSVLObjectList("requests") ;

			if (requestList == null || requestList.size() == 0)
				hasRequest = false ;

			if (hasRequest)
				try
				{
					Thread.sleep(5000) ;
				}
				catch (final Exception ex)
				{
				}
		}
		System.out.println(coId + " ALL Requests processed") ;
	}

}
